package com.ts.api.module.api.entity.bo;

import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.encode.HexUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.entity.po.ApiKeyPO;
import lombok.Data;

/**
 *  消息解密实体
 *
 *  @author Pan
 */
@Data
public class ApiDecryptBO {

    /** 解密后内容 */
    private String content;
    /** 缓存对象 */
    private ApiKeyPO cacheKey;
    /** 解密内容 */
    private String ciphertext;

    public ApiDecryptBO() {
        super();
    }

    public ApiDecryptBO(String ciphertext, ApiKeyPO cacheKey) {
        this.ciphertext = ciphertext;
        this.cacheKey = cacheKey;
    }

    /**
     * API解密内容
     *
     * @return ApiDecryptBO
     */
    ApiDecryptBO aes() {
        AES ecb = AES.createEcb(HexUtils.decode(cacheKey.getApiSecretKey()));
        try {
            this.content = ecb.decryptFromHexStr(ciphertext);
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_DECRYPT_ERROR, e.getMessage());
        }
        Assert.isNotEmpty(this.content, () -> { throw new ApiMsgException(ApiEnum.API_DECRYPT_BODY_EMPTY); });
        return this;
    }

    /**
     * API解密aes
     *
     * @param  ciphertext
     * @param  cacheKey
     * @return ApiDecryptBO
     */
    public static ApiDecryptBO aes(String ciphertext, ApiKeyPO cacheKey) {
        return new ApiDecryptBO(ciphertext, cacheKey).aes();
    }
}
